import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
     private Socket socket = null ;
     // 需要告诉客户端,服务器在哪里
    public TcpEchoClient(String serverIp , int port) throws IOException {
        this.socket = new Socket(serverIp , port);
    }
    public void start(){

        Scanner scan = new Scanner(System.in);
        System.out.println("客户端上线");
        try(InputStream inputStream = socket.getInputStream() ;
            OutputStream outputStream = socket.getOutputStream();){
            Scanner scanResponse = new Scanner(inputStream) ; // 读取响应
            while (true) {
                // 从控制台读取请求
                String request = scan.next();
                // 发送请求, 用writ保持请求里也有换行
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(request);
                writer.flush();
                //读取请求
                String response = scanResponse.next();
                System.out.println("响应:" + response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 7070);
        client.start();
    }

}
